/**
 * 常用工具方法集合
 */

const utils = {
	// 延迟函数
	delay(fn, delay = 300) {
		setTimeout(fn, delay);
	},

	/**
	 * 当一个方法返回false时，多次执行它，以获得正确信息
	 * @return {Promise}
	 */
	loopObtain(fn, maxLoopNumber = 10) {
		return async function(...args) {
			let result, number = 0;
			while (number <= maxLoopNumber && !result) {
				result = await fn(...args);
				number++;
			}
			return result;
		};
	},

	// 成功的提示
	okShow(msg) {
		uni.showToast({
			title: `${msg || '操作成功'}`,
			duration: 2000
		});
	},

	// 失败的提示
	failShow(msg) {
		uni.showToast({
			icon: 'error',
			title: `${msg || '操作失败'}`,
			duration: 2000
		});
	},

	// 分装页面跳转
	next(url, d) {
		let data = JSON.stringify(d);
		uni.navigateTo({
			url: `${url}?data=${data}`
		});
	},

	next1(url, d) {
		let data = JSON.stringify(d);
		uni.reLaunch({
			url: `${url}?data=${data}`
		});
	},

	ToastOk(msg) {
		return new Promise(resolve => {
			uni.showToast({
				title: msg,
				icon: 'success',
				duration: 3000
			});
		});
	},

	ToastFail(msg) {
		return new Promise(resolve => {
			uni.showToast({
				title: msg,
				icon: 'none',
				duration: 3000
			});
		});
	},

	downLoad(url) {
		wx.downloadFile({
			url: url,
			header: {
				Authorization: "Bearer " + uni.getStorageSync('personInfo').accessToken
			},
			success: (res) => {
				if (res.statusCode === 200) {
					var temp = res.tempFilePath;
					wx.saveFile({
						tempFilePath: temp,
						success: (res) => {
							let saveFilePath = res.savedFilePath;
							let suffix = utils.getFileSuffix(saveFilePath);
							wx.openDocument({
								filePath: saveFilePath,
								fileType: suffix,
								showMenu: true,
								success: (res) => {}
							});
						}
					});
				} else {
					wx.showModal({/* ... */}); // 省略相同代码
				}
			},
			fail: () => {/* ... */} // 省略相同代码
		});
	},

	// 打开文档
	daoChu(path) {/* ... */}, // 同上省略具体实现

	// 手机拨号
	PhoneCall(val) {/* ... */}, // 同上省略具体实现

	// 预览图片
	imgShow(path) {/* ... */}, // 同上省略具体实现

	//保存图片到相册
	savePhoto(path, tip) {/* ... */}, // 同上省略具体实现

	// 返回上一页
	back() {
		uni.navigateBack();
	}
};

export default utils;